/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 2013-2014 sagyf Yang. The Four Group.
 */

package app.controllers;

import app.models.sys.AuthUsers;
import com.github.sog.config.StringPool;
import com.github.sog.controller.BasicController;
import com.github.sog.controller.security.AppUser;
import com.github.sog.controller.security.Securitys;
import com.github.sog.kit.date.DateProvider;
import com.github.sog.kit.servlet.RequestKit;
import com.github.sog.libs.AppFunc;
import com.google.common.base.Strings;
import com.jfinal.aop.Before;
import com.jfinal.ext.interceptor.Restful;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * <p>
 * .
 * </p>
 *
 * @author sagyf yang
 * @version 1.0 2014-03-27 23:22
 * @since JDK 1.6
 */
@Before(Restful.class)
public class LoginController extends BasicController {
    private static final Logger logger = LoggerFactory.getLogger(LoginController.class);
    public static final boolean LOGIN = Securitys.isLogin();

    public void index() {
        if (LOGIN) {
            if (Securitys.isRole("customer")) {

                redirect("/customer/index");
            } else if (Securitys.isRole("admin")) {
                redirect("/admin/home");
            } else {
                logger.error("非法登录！");
                SecurityUtils.getSubject().logout();
                redirect("/login?error=2&name=");
            }
        } else {
            int mask = getParaToInt("error", 0);
            String name = getPara("name", StringPool.EMPTY);
            setAttr("name", name);
            if (mask > 0) {
                setAttr("error", (mask == 2) ? "用户名或者密码错误!" : "请输入登录账号和登录密码");
            }
            render("/admin/login.ftl");
        }
    }

    public void save() {
        String password = getPara(FormAuthenticationFilter.DEFAULT_PASSWORD_PARAM);
        String username = getPara(FormAuthenticationFilter.DEFAULT_USERNAME_PARAM);
        if (Strings.isNullOrEmpty(username) || Strings.isNullOrEmpty(password)) {
            redirect("/login?error=1&name=" + username);
            return;
        }
        boolean rememberMe = StringUtils.equals(getPara(FormAuthenticationFilter.DEFAULT_REMEMBER_ME_PARAM, "off"), "on");
        UsernamePasswordToken token = new UsernamePasswordToken(username, password, rememberMe);
        final Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
        } catch (AuthenticationException e) {
            logger.error("用户名或者密码错误！", e);
            redirect("/login?error=2&name=" + username);
            return;
        }
        // login success.
        AppUser appUser = Securitys.getLoginMember();
        AuthUsers loginSucc = new AuthUsers();
        loginSucc.set(AppFunc.TABLE_PK_COLUMN, appUser.getId());
        loginSucc.set("last_login_time", DateProvider.DEFAULT.getCurrentDate());
        loginSucc.set("last_login_ip", RequestKit.getRemoteAddr(getRequest()));
        loginSucc.update();


        //为了跳转到 customer 页面，默认都是customer
        if (subject.hasRole("customer")) {
            redirect("/customer/index");
        } else if (subject.hasRole("admin")) {
            redirect("/admin/home");
        } else {
            logger.error("非法登录！");
            subject.logout();
            redirect("/login?error=2&name=" + username);
        }
    }
}
